import Mocha from '../../modules/mocha.js';
import Util from '../../modules/util.js';
import RTLog from '../../modules/rt_log.js';
import ProductResultCache from '../../modules/product_result_cache.js';
import { videoAdWatchCount } from './video_ad.js';
import { parseSetting } from './setting.js';
const App = getApp();

Page({
    mpid: '',
    data: {
        showCancel: true,
        result: '',
        showFull: false,
        imageLoading: false,
        showAdButton: false,
        showConfirm: false,
        videoAdId: '',
        confirmTitle: '',
        confirmContent: '',
        confirmBtnText: '',
        cancelBtnText: '',
        reShowAdText: '',
        themeColor: getApp().globalData.themeColor,
        countDownTime: null,
        loadingStatus: false,
        customErrorPopup: false,
        errContext: ''
    },
    settings: parseSetting(),
    videoAdWatchCounter: null,
    videoAd: null, // 激励视频广告
    interstitialAd: null, // 插屏广告
    adProb: 100, // 激励视频广告弹出概率，默认100%弹出
    timerShowAd: null, // 显示广告的倒计时
    gotoWeb: null,
    randomUrl: null,
    showedConfirm: false,
    onLoad(options) {
        this.setData({ loadingStatus: true });
        this.adState = false;
        wx.setNavigationBarTitle({
            title: App.globalData.testTitle
        });
        this.videoAdWatchCounter = new videoAdWatchCount(
            `resultPageVideoAdWatchCountBy${new Date().format('yyyyMMdd')}`
        );

        // 页面访问次数
        this.visitCounter = new videoAdWatchCount(
            `resultPageVisitCountBy${new Date().format('yyyyMMdd')}`
        );
        this.visitCounter.incrCount();

        this.mpid = options.mpid;
        // if (!App.globalData.productInfo) {
        //     Mocha.getProductConfig(this.mpid)
        //         .then((res) => {
        //             App.globalData.productInfo = res;
        //             getApp().mox.stat(`result page get_mocha_product success`);
        //         })
        //         .catch((err) => {
        //             // getApp().mox.stat(
        //             //     `result page get_mocha_product fail:${err.errMsg || err.msg || '未知错误'}`
        //             // );
        //             getApp().mox.stat(`result page get_mocha_product fail`);
        //             RTLog.error(
        //                 'result page get_mocha_product fail：',
        //                 err.errMsg || err.msg || '未知错误'
        //             );
        //         });
        // }

        // 获取广告详情
        this.onGetAdsConfig();

        // wx.showLoading({
        //     title: '分析中...',
        //     mask: true
        // });
        if (options.url) {
            this.setData({
                result: decodeURIComponent(options.url),
                showFull: true
            });
        } else {
            // 获取产品配置项
            this.onGetConfig();

            // 创建结果页面
            this.onCreateMakeImageTask();
        }
    },
    onShow() {
        if (this.settings?.confirmModal?.autoShowVideoAdCountDown) {
            this.confirmCountDown = null;
            this.setData({
                countDownTime: null
            });
        }
    },
    onGetAdsConfig() {
        Mocha.getAdsConfig()
            .then((ads) => {
                const ad = ads['pages/result/result'];
                ad && ad.ad_id && this.setData({ videoAdId: ad.ad_id });
                if (ad && ad.ad_id) {
                    ad.ad_type = (ad.ad_type || '').toLowerCase();
                    if (ad.ad_type == 'rewarded-video' && wx.createRewardedVideoAd) {
                        this.videoAd = wx.createRewardedVideoAd({ adUnitId: ad.ad_id });
                        this.videoAd.onLoad((res) => {
                            this.adState = true;
                        });
                        this.videoAd.onError((err) => {
                            this.adState = false;
                            this.showResult();
                        });
                        this.videoAd.onClose((res) => {
                            if (res && res.isEnded) {
                                this.videoAdWatchCounter.incrCount();
                                this.showResult();
                            } else {
                                this.showConfirm('', '你未看完广告，要看完才可以查看分析结果哦~');
                            }
                        });
                    }
                    if (ad.ad_type == 'interstitialad' && wx.createInterstitialAd) {
                        // 在页面onLoad回调事件中创建插屏广告实例
                        this.interstitialAd = wx.createInterstitialAd({
                            adUnitId: ad.ad_id
                        });
                        this.interstitialAd.onLoad((res) => {});
                        this.interstitialAd.onError((err) => {});
                    }
                }
                getApp().mox.stat(`result page get_ads_config success`);
            })
            .catch((err) => {
                // getApp().mox.stat(
                //     `result page get_ads_config fail：${err.msg || err.errMsg || '未知错误'}`
                // );
                getApp().mox.stat(`result page get_ads_config fail`);
                RTLog.error(
                    'result page get_ads_config fail：',
                    err.errMsg || err.msg || '未知错误'
                );
            });
    },

    // 获取产品配置项
    onGetConfig() {
        const cfg = App.globalData.cfgData;
        let newSuggest = {};
        let { suggest, product_layout } = cfg;
        if (product_layout) {
            newSuggest =
                suggest &&
                suggest.find((value) => {
                    return value.mpid === this.mpid;
                });
        } else {
            newSuggest =
                suggest &&
                suggest[suggest.type].find((value) => {
                    return value.mpid === this.mpid;
                });
        }
        // if (!cfg?.pageSettings) {
            // 获取默认pageSettings
            Mocha.getConfig()
                .then((cfg) => {
                    this.settings = cfg.pageSettings?.result;
                    this.setData({
                        // showCancel: this.settings.confirmModal.showCancel,
                        // confirmBtnText: this.settings.confirmModal.confirmText,
                        // cancelBtnText: this.settings.confirmModal.cancelText,
                        // reShowAdText: this.settings.reShowAdText,
                        themeColor: cfg.theme.main_color
                    });
                    wx.setNavigationBarColor({
                        frontColor: cfg.theme.navibar_text_color || '#000000',
                        backgroundColor: '#F5F5F5'
                    });
                    getApp().mox.stat(`result page get_mocha_h5_config success`);
                })
                .catch((err) => {
                    console.log('err-------', err);
                    // getApp().mox.stat(
                    //     `result page get_mocha_h5_config fail：${
                    //         err.msg || err.errMsg || '未知错误'
                    //     }`
                    // );
                    getApp().mox.stat(`result page get_mocha_h5_config fail`);
                    RTLog.error(
                        'result page get_mocha_h5_config fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                });
        // } else {
            // wx.hideLoading();
            // 获取当前小程序pageSettings
            // this.settings = newSuggest.pageSettings.result;
            // let cancelAction = this.settings.confirmModal.cancelAction.type;
            // this.setData({
            //     showCancel: this.settings.confirmModal.showCancel,
            //     confirmBtnText: this.settings.confirmModal.confirmText,
            //     cancelBtnText: this.settings.confirmModal.cancelText,
            //     reShowAdText: this.settings.reShowAdText
            // });
            // if (cancelAction === 'hide') {
            // } else if (cancelAction === 'show_result') {
            //     let adConfig = this.settings.confirmModal.adConfig;
            //     this.adState = false;
            //     this.videoAd = null;
            //     this.setData({
            //         showConfirm: false,
            //         showAdButton: false,
            //         videoAdId: null,
            //         imageLoading: true
            //     });
            //     this.showResult();
            //     this.adIntersAdPlay(adConfig);
            // } else if (cancelAction === 'goto_web') {
            //     this.gotoWeb = 'goto_web';
            //     this.setData({
            //         showAdButton: false,
            //         videoAdId: null,
            //         imageLoading: true
            //     });
            //     this.videoAd &&
            //         this.showConfirm(
            //             this.settings.confirmModal.title,
            //             this.settings.confirmModal.content
            //         );
            //     this.showedConfirm = true;
            //     let newArgs = this.settings.confirmModal.cancelAction.args;
            //     if (Array.isArray(newArgs)) {
            //         let randomArgs = newArgs[Math.floor(Math.random() * newArgs.length)];
            //         this.randomUrl = randomArgs;
            //     } else {
            //         this.showResult();
            //     }
            // }
        // }
    },

    // 创建结果页面
    onCreateMakeImageTask() {
        let answers = App.globalData.answers || ['1', '1', '1', '1'];
        if (answers[0] != -1) {
            answers.unshift(-1);
        }
        Mocha.createMakeImageTask(this.mpid, answers)
            .then((taskId) => {
                Mocha.getMakeImageTaskResult(taskId)
                    .then((res) => {
                        if (res.url) {
                            this.setData({
                                result: res.url,
                                imageLoading: true
                            });
                            ProductResultCache.setResult(this.mpid, res.url);
                            if (this.interstitialAd) {
                                this.interstitialAd
                                    .show()
                                    .then(() => {
                                        getApp().mox.stat('ShowInterstitialAd_Success');
                                    })
                                    .catch((err) => {
                                        // getApp().mox.stat(
                                        //     'ShowInterstitialAd_Error_' + (err.errCode || 'unknown')
                                        // );
                                        getApp().mox.stat('ShowInterstitialAd_Error');
                                        RTLog.error(
                                            'ShowInterstitialAd_Error_：',
                                            err.errCode || 'unknown'
                                        );
                                    });
                            }

                            // 用户触发广告后，显示激励视频广告

                            if (this.videoAd) {
                                const prop = Math.random() * 100;
                                if (prop <= this.adProb) {
                                    getApp().mox.stat('VideoAdProp-Hit');
                                    if (
                                        this.settings.confirmModal.cancelAction.type ===
                                        'show_result'
                                    ) {
                                        if (
                                            wx.createInterstitialAd &&
                                            this.settings.confirmModal.adConfig.ad_type ===
                                                'interstitialad'
                                        ) {
                                            const interstitialAd = wx.createInterstitialAd({
                                                adUnitId: this.settings.confirmModal.adConfig.ad_id
                                            });
                                            interstitialAd.onLoad((res) => {});
                                            interstitialAd.onError((err) => {
                                                // getApp().mox.stat(
                                                //     'LoadInterstitialAd_Error_' +
                                                //         (err.errCode || 'unknown')
                                                // );
                                                getApp().mox.stat('LoadInterstitialAd_Error');
                                            });
                                            interstitialAd
                                                .show()
                                                .then(() => {
                                                    this.setData({
                                                        showFull: true
                                                    });
                                                    getApp().mox.stat('ShowInterstitialAd_Success');
                                                })
                                                .catch((err) => {
                                                    this.setData({
                                                        showFull: true
                                                    });
                                                    // getApp().mox.stat(
                                                    //     'ShowInterstitialAd_Error_' +
                                                    //         (err.errCode || 'unknown')
                                                    // );
                                                    getApp().mox.stat('ShowInterstitialAd_Error');
                                                });
                                        }
                                    } else {
                                        !this.showedConfirm &&
                                            this.showConfirm(
                                                this.settings.confirmModal.title,
                                                this.settings.confirmModal.content
                                            );
                                    }
                                } else {
                                    getApp().mox.stat('VideoAdProp-Miss');
                                    this.showResult();
                                }
                            } else {
                                this.showResult();
                            }
                            getApp().mox.stat('result page get_result_image_url success');
                        } else {
                            getApp().mox.stat('result page get_result_image_url fail：no url');
                            RTLog.error('result page get_result_image_url fail：', 'no url');
                        }
                    })
                    .catch((err) => {
                        // getApp().mox.stat(
                        //     `result page get_result_image_url fail:${
                        //         err.errMsg || err.msg || '未知错误'
                        //     }`
                        // );
                        if ((err.errMsg || err.msg) == '查询出错') return;
                        getApp().mox.stat(`result page get_result_image_url fail`);
                        RTLog.error(
                            'result page get_result_image_url fail:',
                            err.errMsg || err.msg || '未知错误'
                        );
                    });
                getApp().mox.stat('result page make_task success');
            })
            .catch((err) => {
                this.setData({
                    result: 'https://qncdn.mopic.mozigu.net/f/mr6kod18k32ah1s63tg/1263eef5e1de/kf_ty.png'
                });
                // getApp().mox.stat(
                //     `result page make_task fail:${err.errMsg || err.msg || '未知错误'}`
                // );
                getApp().mox.stat(`result page make_task fail`);
                RTLog.error('result page make_task fail：', err.errMsg || err.msg || '未知错误');
            });
    },

    // 单个产品type类型为show_result的插屏广告
    adIntersAdPlay(ad_Config) {
        if (ad_Config && ad_Config.ad_type === 'interstitialad') {
            this.interstitialAd = wx.createInterstitialAd({
                adUnitId: ad_Config.ad_id
            });
            if (this.interstitialAd) {
                this.interstitialAd
                    .show()
                    .then(() => {
                        getApp().mox.stat('ShowInterstitialAd_Success');
                    })
                    .catch(() => {
                        this.interstitialAd
                            .load()
                            .then(() => {
                                this.interstitialAd.show().then(() => {
                                    getApp().mox.stat('ShowInterstitialAd_Success');
                                });
                            })
                            .catch((err) => {
                                // getApp().mox.stat(
                                //     'ShowInterstitialAd_Error_singer' + (err.errCode || 'unknown')
                                // );
                                getApp().mox.stat('ShowInterstitialAd_Error_singer');
                                this.showResult();
                            });
                    });
                this.interstitialAd.onError((err) => {
                    // getApp().mox.stat(
                    //     'LoadInterstitialAd_Error_singer' + (err.errCode || 'unknown')
                    // );
                    getApp().mox.stat('LoadInterstitialAd_Error_singer');
                    this.showResult();
                });
            }
        } else {
            this.showResult();
        }
    },

    onSaveImage() {
        Util.saveImage(this.data.result, '保存完成')
            .then(() => {
                getApp().mox.stat('result page save_image success');
            })
            .catch((err) => {
                if (err?.errMsg?.includes('deny')) {
                    // getApp().mox.stat(`result page save_image fail: user refuse auth`);
                    // RTLog.error('result page save_image fail：', 'user refuse auth');
                } else {
                    // getApp().mox.stat(
                    //     `result page save_image fail:${err.errMsg || err.msg || '未知错误'}`
                    // );
                    getApp().mox.stat(`result page save_image fail`);
                    RTLog.error(
                        'result page save_image fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                }
            });
    },

    onShareAppMessage() {
        getApp().mox.stat('result page share_result');

        return {
            title: App.globalData.productInfo.h5_config.title,
            imageUrl: App.globalData.shareImageUrl,
            path: `/pages/product/product?mpid=${this.mpid}`
        };
    },
    // 显示激励视频
    onShowVideoAd() {
        if (this.timerShowAd) {
            clearInterval(this.timerShowAd);
            this.timerShowAd = null;
        }

        // this.countTimeState = true
        this.setData({
            showAdButton: false,
            showConfirm: false
        });
        if (this.videoAd) {
            wx.showLoading({
                title: '加载中...',
                mask: true
            });
            this.videoAd
                .show()
                .then(() => {
                    getApp().mox.stat('show_video_ad_success');
                    wx.hideLoading();
                })
                .catch(() => {
                    this.videoAd
                        .load()
                        .then(() => {
                            wx.hideLoading();
                            this.videoAd.show().then(() => {
                                getApp().mox.stat('show_video_ad_success');
                            });
                        })
                        .catch((err) => {
                            wx.hideLoading();
                            // getApp().mox.stat(
                            //     `show_video_ad_error:${err.errMsg || err.msg || '未知错误'}`
                            // );
                            getApp().mox.stat(`show_video_ad_error`);
                            RTLog.error(
                                'show_video_ad_error：',
                                err.errMsg || err.msg || '未知错误'
                            );
                            this.showResult();
                        });
                });
        }
    },
    // 显示结果分析中弹窗
    showConfirm(title, tips) {
        this.setData({
            confirmTitle: title,
            showConfirm: true,
            confirmContent: tips
        });
        if (this.settings.confirmModal.autoShowVideoAdCountDown) {
            this.setData({
                countDownTime: this.settings.confirmModal.autoShowVideoAdCountDown
            });
            this.confirmCountDown();
        }
    },
    // 激励视频弹窗广告倒计时
    confirmCountDown() {
        this.timerShowAd = null;
        if (this.data.countDownTime > 0) {
            this.timerShowAd = setInterval(() => {
                this.setData({
                    countDownTime: this.data.countDownTime - 1
                });
                if (!this.data.countDownTime) {
                    this.onShowVideoAd();
                }
            }, 1000);
        }
    },
    showResult() {
        this.setData({
            showConfirm: false,
            showFull: true
        });
    },
    onLoadImageFinish() {
        this.setData({
            showFull: true,
            loadingStatus: false
        });
        // wx.hideLoading();
        // this.setData({
        //     imageLoading: false
        // });
        getApp().mox.stat('result page load_image success');
    },
    touchMove() {},
    onLoadImageFail(evt) {
        let { errMsg = '未知错误' } = evt.detail;
        // getApp().mox.stat(`result page load_image fail: ${errMsg}`);
        getApp().mox.stat(`result page load_image fail`);
        RTLog.error('result page load_image fail：', errMsg);
        this.setData({
            errContext: '图片加载失败，请稍后重试~',
            customErrorPopup: true,
            result: 'https://qncdn.mopic.mozigu.net/f/mr6kod18k32ah1s63tg/1263eef5e1de/kf_ty.png'
        });
    },
    onPreviewImage() {
        wx.previewImage({
            urls: [this.data.result]
        });
        getApp().mox.stat('result page preview_image');
    },
    // 结果分析弹窗取消按钮的事件
    onHideConfirmMask() {
        if (this.timerShowAd) {
            clearInterval(this.timerShowAd);
            this.timerShowAd = null;
        }
        let gotoWebStr =
            this.settings &&
            this.settings.confirmModal &&
            this.settings.confirmModal.cancelAction.type;
        if (gotoWebStr === 'show_result') {
            // 取消以后立即给图
            this.setData({
                showConfirm: false,
                showFull: true
            });
        } else if (gotoWebStr === 'goto_web') {
            wx.navigateTo({
                url: `/pages/web/web?url=${this.randomUrl}`
            });
        } else {
            this.setData({
                showConfirm: false,
                showAdButton: true
            });
        }
    }
});
